package grpc

import (
	"context"
	"group-buying/internal/models/dao"
	"group-buying/internal/models/services"
	user1 "group-buying/internal/proto/user"
)

type UserServer struct {
	user1.UnimplementedRegisterServerServer
}

func (s *UserServer) Register(ctx context.Context, req *user1.RegisterReq) (*user1.RegisterResp, error) {
	user := dao.User{
		Name: req.Name,
		Pass: req.Pass,
	}
	err := services.CreateUser(user)
	if err != nil {
		return &user1.RegisterResp{
			Code: -1,
			Msg:  "创建用户失败",
		}, err
	}
	resp := &user1.RegisterResp{
		Code: 200,
		Msg:  "创建用户成功",
	}
	return resp, err
}

func (s *UserServer) CreatGroup(ctx context.Context, req *user1.CreatGroupReq) (*user1.CreatGroupResp, error) {
	group := dao.Group{
		Name:   req.Name,
		State:  int(req.State),
		Num:    int(req.Num),
		UserId: int(req.UserId),
	}
	err := services.CreateGroup(group)
	if err != nil {
		return &user1.CreatGroupResp{
			Code: -1,
			Msg:  "添加失败",
		}, err
	}
	resp := &user1.CreatGroupResp{
		Code: 200,
		Msg:  "添加成功",
	}
	return resp, err
}

func (s *UserServer) GroupList(ctx context.Context, req *user1.GroupListReq) (*user1.GroupListResp, error) {
	list, err := services.GroupList(req.Name, int(req.Page), int(req.PageSize))
	if err != nil {
		return &user1.GroupListResp{
			Code: -1,
			Msg:  "列表展示失败",
			Data: nil,
		}, err
	}
	var userList []*user1.UserInfo
	for _, v := range list {
		userList = append(userList, &user1.UserInfo{
			Name:   v.Name,
			State:  int32(v.State),
			Num:    int32(v.Num),
			UserId: int32(v.UserId),
		})
	}
	resp := &user1.GroupListResp{
		Code: 200,
		Msg:  "列表展示成功",
		Data: userList,
	}
	return resp, err
}
